<template>
    <base-breadcrumb :title="titleName">
        <a-row :gutter="20" class="page-height">
            <a-col span="6" class="goods-search-left">
                <a-card v-loading="getTreeLoading" class="page-height-tree">
                    <!-- <title-name title="新技术类型" /> -->
                    <a-input-search style="margin-bottom: 8px" @change="onChange" />
                    <div>
                        <a-tree
                            :expanded-keys="expandedKeys"
                            :auto-expand-parent="autoExpandParent"
                            :tree-data="treeData"
                            :selected-keys="selectedKeys"
                            @select="onSelect"
                            @expand="onExpand"
                        >
                            <template slot="title" slot-scope="{ title }">
                                <span v-if="title.indexOf(searchValue) > -1">
                                    {{ title.substr(0, title.indexOf(searchValue)) }}
                                    <span style="color: #f50">{{ searchValue }}</span>
                                    {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
                                </span>
                                <span v-else>{{ title }}</span>
                            </template>
                        </a-tree>
                    </div>
                </a-card>
            </a-col>
            <a-col span="18" class="page-height-list-wrapper">
                <searchData ref="searchDataRef" :search-data="searchArr" @search="search" />
                <a-card :bordered="false"  class="page-height-list">
                    <!-- <title-name title="新技术应用情况列表" /> -->
                    <!-- :export-config="{
                            use: true,
                            all: '新技术应用情况列表-导出全部',
                            select: '新技术应用情况列表-导出选中',
                            customColumns
                        }"
                        :export-config-text="{ select: '导出选中', all: '导出全部' }"
                        :exportPermission="{select: 'stm_007_exp_09',all: 'stm_006_expall_08'}" -->
                    <list-table
                        ref="table"
                        :columns="columns"
                        :outSelectedRowKeys.sync="selectedRowKeys"
                        :request="loadData"
                         :start-index="0"
                        :is-show-count-bar="false"
                        :export-config="{use: true}"
                    >
                        <template slot="prefix">
                            <a-button
                                v-btnPermission="'stm_006_add_01'"
                                type="primary"
                                icon="plus"
                                @click="handleEdit(null, 0)"
                            >
                                新技术应用情况上报
                            </a-button>
                            <a-button
                                v-btnPermission="'stm_006_exp_07'"
                                type="primary"
                                icon="download"
                                :disabled="selectedRowKeys.length<1"
                                @click="exportExtensionFn('select')"
                                :loading="exportLoading"
                            >
                                导出选中
                            </a-button>
                            <a-button
                                v-btnPermission="'stm_006_expall_08'"
                                type="primary"
                                icon="download"
                                @click="exportExtensionFn('all')"
                                :loading="exportLoading"
                            >
                                导出全部
                            </a-button>
                        </template>
                        <template slot="bottom">
                            <b-summary :selectedRowKeys="selectedRowKeys"></b-summary>
                        </template>
                        <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
                        <span slot="status" slot-scope="text">
                            <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
                        </span>
                        <div slot="action" slot-scope="text, record">
                            <MoreButton>
                            <a @click="lookDetail(record)">查看</a>
                            <a v-if="record.statusCode == 0 || record.statusCode == 3"
                                  v-btn-permission="'stm_006_edi_02'"
                                  @click="handleEdit(record, 1)">
                              编辑
                            </a>
                            <a v-btn-permission="'stm_006_upd_06'" v-if="record.statusCode == 2" @click="handleUpdate(record)">更新</a>
                            <!--              <span @click="handleUpdate(record)">更新</span>-->
                            <a v-btn-permission="'stm_006_del_05'" v-if="record.statusCode == 0" @click="handleRemove(record.id)">删除</a>
                            <!-- 当状态为审批中 -->
                            <a
                                v-if="record.statusCode != '0'"
                                @click="$bus.$emit('showApprovalDetailsDialog', record.id)"
                                >审批详情</a
                            >
                            </MoreButton>
                        </div>
                        <!-- 状态 -->
                        <template slot="statusCode" slot-scope="text, record">
                            <status-display :status-code="record.statusCode" is-approval />
                        </template>
                    </list-table>
                </a-card>
            </a-col>
        </a-row>
        <addPost :visible.sync="visible" :state="state" :form="selectRow" @ok="search" />
        <updateDialog :visible.sync="updateVisible" :state="state" :form="selectRow" @ok="search" />
        <detail :visible.sync="lookDetailVisible" :form="selectRow" />
    </base-breadcrumb>
</template>

<script>
import { STable } from '@/components'
import { getTechnologyList, deleteTechnology, getStatistics, treeList,exportExtension } from '@/api/technology'
import addPost from './addPost'
import ARow from 'ant-design-vue/es/grid/Row'
import { themeChoose } from '@/mixin/mixin'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import OrgTreeSelect from '@/components/OrgTreeSelect'
import SelectTechnicalName from '@/components/Select/SelectTechnicalName' // 模板
import StatusDisplay from '@/components/StatusDisplay'
import BasePage from '@/views/basePage'
import updateDialog from '@/views/science/achievementsExtend/technologyApplication/updateDialog' // 基础配置
import detail from './detail'
import summary from './summary'

const columns = [
    {
        title: '序号',
        width: '65px',
        scopedSlots: { customRender: 'serial' }
    },
    {
        title: '项目名称',
        width: '160px',
        dataIndex: 'projectName'
    },
    {
        title: '所属分公司',
        width: '120px',
        dataIndex: 'branchCompany'
    },
    {
        title: '新技术名称',
        width: '200px',
        dataIndex: 'technicalName'
    },
    {
        title: '应用数量 ',
        width: '100px',
        dataIndex: 'applicationNumber',
        customRender(text, record, index) {
            return record.applyUnit ? record.applicationNumber + record.applyUnit : record.applicationNumber
        }
    },
    {
        title: '施工日期',
        width: '190px',
        dataIndex: 'constructionDate'
    },
    {
        title: '投入经费（万元）',
        width: '100px',
        dataIndex: 'investmentOutlay'
    },
    {
        title: '产生效益（万元）',
        width: '100px',
        dataIndex: 'productionBenefit'
    },
    {
        title: '状态',
        dataIndex: 'statusCode',
        width: '140px',
        scopedSlots: { customRender: 'statusCode' }
    },
    {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: '180px',
        align: 'center',
        scopedSlots: { customRender: 'action' }
    }
]
export default {
    extends: new BasePage(),
    mixins: [themeChoose],
    name: 'a' + Date.now(),
    components: {
        ARow,
        STable,
        addPost,
        StatusDisplay,
        updateDialog,
        detail,
        'b-summary': summary
    },
    data() {
        this.columns = columns
        return {
            exportLoading:false,
            removeApi: { remove: deleteTechnology }, // 删除草稿api
            titleName: '',
            visible: false,
            updateVisible: false,
            lookDetailVisible: false,
            getTreeLoading: false,
            queryParam: {},
            loadData: (parameter) => {
                let projectDate = this.queryParam.projectDate
                if (projectDate) {
                    this.queryParam.startTime = projectDate[0]
                    this.queryParam.endTime = projectDate[1]
                    delete this.queryParam.projectDate
                }
                if (this.selectTree) {
                    this.queryParam.treeId = this.selectTree.id
                } else {
                    delete this.queryParam.treeId
                }
                const requestParameters = Object.assign({}, parameter, this.queryParam)
                return getTechnologyList(requestParameters)
            },

            searchArr: [
                // 搜索框
                // {
                //     name: '所属分公司',
                //     valueKey: 'branchCompanyId',
                //     placeholder: '请选择',
                //     type: SelectSubCompany
                // },
                {
                  name: '所属单位',
                  valueKey: 'searchQuery',
                  type: OrgTreeSelect,
                },
                // {
                //     name: '项目名称',
                //     valueKey: 'projectId',
                //     placeholder: '请选择',
                //     type: SelectProject
                // },
                {
                    name: '新技术名称',
                    valueKey: 'technicalName',
                    placeholder: '请选择',
                    type: SelectTechnicalName
                },
                {
                    name: '施工日期',
                    value: 'time',
                    type: 'date',
                    attr: { valueFormat: 'YYYY-MM-DD' }
                }
            ],
            selectRow: {},
            state: 0,

            treeData: [],
            selectedKeys: [],
            replaceFields: {
                children: 'children',
                title: 'name',
                key: 'id'
            },

            expandedKeys: [],
            expandedKeysTemp: [],
            searchValue: '',
            autoExpandParent: true,
            dataList: [],
            selectTree: null,

            // customColumns: [
            //   { title: '新技术名称', dataIndex: 'technicalName' },
            //   { title: '施工时间', dataIndex: 'constructionDate' },
            //   // { title: '应用部位', dataIndex: 'technicalName' },
            //   { title: '计划量（实物量）', dataIndex: 'entityMeasure' },
            //   // { title: '实际数量（实物量）', dataIndex: 'entityMeasure' },
            //   { title: '应用工程量（㎡）', dataIndex: 'applicationNumber' },
            //   { title: '投入经费（万元）', dataIndex: 'investmentOutlay' },
            //   { title: '效益额（万元）', dataIndex: 'productionBenefit' }
            //   // { title: '应用情况', dataIndex: 'statusName' },
            // ],
            customColumns: [
                { title: '应用技术', dataIndex: 'technicalName' },
                { title: '分公司', dataIndex: 'branchCompany' },
                { title: '项目', dataIndex: 'projectName' },
                { title: '应用工程量', dataIndex: 'applicationNumber' },
                { title: '实物量', dataIndex: 'entityMeasure' },
                { title: '投入经费（万元）', dataIndex: 'investmentOutlay' },
                { title: '生产效益（万元）', dataIndex: 'productionBenefit' },
                { title: '应用部位', dataIndex: 'applicationSite' },
                { title: '应用情况', dataIndex: 'applicationSituation' },
                { title: '备注', dataIndex: 'remark' }
            ],
            selectedRowKeys: []
        }
    },
    mounted() {
        this.getTree()
    },
    methods: {
      /**
       * 新技术应用情况导出
       * @param parameter
       */
       async exportExtensionFn(ident){
        this.exportLoading = true;
        setTimeout(() => {
            this.exportLoading = false;
        }, 3000);
        let param = this.$refs.searchDataRef.form.getFieldsValue();
        if (ident === 'select'){
            param.ids = this.selectedRowKeys  
        }
          let res = await exportExtension(param)
          this.handleDownload(res)
      },
    /**
     * 转义下载
     * @param parameter
     */
     handleDownload(res){
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename.substring(filename.indexOf("''") + 2) // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
        onChange(e) {
            const value = e.target.value
            if (!value) {
                this.autoExpandParent = true
                this.expandedKeys = this.$clone(this.expandedKeysTemp)
                this.searchValue = ''
            } else {
                const expandedKeys = this.dataList
                    .map((item) => {
                        if (item.title.indexOf(value) > -1) {
                            return this.getParentKey(item.key, this.treeData)
                        }
                        return null
                    })
                    .filter((item, i, self) => item && self.indexOf(item) === i)
                Object.assign(this, {
                    expandedKeys,
                    searchValue: value,
                    autoExpandParent: true
                })
            }
        },
        generateList(data) {
            for (let i = 0; i < data.length; i++) {
                const node = data[i]
                const key = node.key
                const title = node.title
                // this.dataList.push({ key, title: key })
                this.dataList.push({ key, title })
                if (node.children) {
                    this.generateList(node.children)
                }
            }
        },
        getParentKey(key, tree) {
            let parentKey
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i]
                if (node.children) {
                    if (node.children.some((item) => item.key === key)) {
                        parentKey = node.key
                    } else if (this.getParentKey(key, node.children)) {
                        parentKey = this.getParentKey(key, node.children)
                    }
                }
            }
            return parentKey
        },
        async getTree(expandedId) {
            return new Promise(async (resolve) => {
                this.getTreeLoading = true
                let res = await treeList()
                this.getTreeLoading = false
                if (res.code === this.SUCCESS_CODE) {
                    this.treeData = this.replaceList(res.data)
                    this.selectedKeys = this.selectedKeys.length ? this.selectedKeys : [this.treeData[0].id]
                    this.expandedKeys = this.expandedKeys.length ? this.expandedKeys : [this.treeData[0].id]
                    if (expandedId) {
                        this.expandedKeys.push(expandedId)
                    }
                    if (!this.selectTree) {
                        this.selectTree = { ...this.treeData[0], dataRef: { children: [1] } }
                    }
                    this.generateList(this.treeData)
                }
                resolve()
            })
        },
        replaceList(list) {
            return list.map((v) => {
                v.scopedSlots = { title: 'title' }
                v.key = v[this.replaceFields.key]
                v.title = v[this.replaceFields.title]
                if (v.children && v.children.length) {
                    v.children = this.replaceList(v.children)
                }
                return v
            })
        },
        onSelect(selectedKeys, info) {
            this.selectedKeys = selectedKeys
            if (selectedKeys.length) {
                this.selectTree = info.selectedNodes[0].data.props
            } else {
                this.selectTree = null
            }
            this.$refs.table.getData(null, true)
        },
        onExpand(expandedKeys) {
            this.expandedKeys = expandedKeys
            this.expandedKeysTemp = expandedKeys
            this.autoExpandParent = false
        },

        search(values) {
            this.queryParam = values || {}
            this.$refs.table.getData(null, true)
        },
        handleEdit(record = null, state = 0) {
            this.visible = true
            this.selectRow = record ? this.$clone(record) : null
            this.state = state
        },
        lookDetail(record = null) {
            this.lookDetailVisible = true
            this.selectRow = record ? this.$clone(record) : null
        },
        handleUpdate(record = null) {
            this.updateVisible = true
            this.selectRow = record ? this.$clone(record) : null
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .ant-radio-wrapper {
    display: block;
    text-overflow: ellipsis;
    overflow: hidden;
    width: 100%;
    margin-bottom: 12px !important;
}

.left-box /deep/ .ant-form-item .ant-form-item-control-wrapper {
    width: 100%;
}
/deep/.export-btn{
    display: none;
}
</style>